<script lang="ts" setup>
import type {
  SysDeptTreeVo,
} from '#/system/dept'
import type {
  SysPostVo,
} from '#/system/post'
import type {
  SysRoleVo,
} from '#/system/role'
import type {
  SysUserPageQo,
} from '#/system/user'
import {
  getSysDeptTreeApi,
} from '@/api/system/dept'
import {
  getSysPostListApi,
} from '@/api/system/post'
import {
  getSysRoleListApi,
} from '@/api/system/role'
import {
  deleteSysUserApi,
  disableSysUserApi,
  enableSysUserApi,
  getSysUserPageListApi,
} from '@/api/system/user'
import { Edit } from '@element-plus/icons-vue'
import Details from './details.vue'
import Tree from './tree.vue'

defineOptions({
  name: 'SystemUser',
})

const columns: TableColumnType[] = [
  {
    type: 'selection',
    fixed: 'left',
    prop: 'selection',
  },
  {
    label: '用户名',
    align: 'center',
    prop: 'username',
    width: 200,
  },
  {
    label: '昵称',
    align: 'center',
    prop: 'name',
    width: 200,
  },
  {
    label: '手机号码',
    align: 'center',
    prop: 'phone',
    width: 200,
  },
  {
    label: '邮箱',
    align: 'center',
    prop: 'email',
    width: 200,
  },
  {
    label: '生日',
    align: 'center',
    prop: 'birthday',
    width: 250,
  },
  {
    label: '机构',
    align: 'center',
    prop: '_deptNameList',
    type: 'tag',
  },
  {
    label: '岗位',
    align: 'center',
    prop: '_postNameList',
    type: 'tag',
  },
  {
    label: '角色',
    align: 'center',
    prop: '_roleNameList',
    type: 'tag',
  },
  {
    label: '性别',
    align: 'center',
    prop: 'sex',
    type: 'dict',
    dictType: 'user_sex',
    width: 120,
  },
  {
    label: '状态',
    prop: 'status',
    align: 'center',
    type: 'dict',
    dictType: 'status',
    width: 120,
  },
  {
    label: '操作',
    prop: 'operation',
    align: 'center',
    type: 'slot',
    fixed: 'right',
    width: 200,
  },
]
const detailsRef = $ref<InstanceType<typeof Details>>()
let selectionList = $ref<string[]>([])
let roleList = $ref<SysRoleVo[]>([])
let postList = $ref<SysPostVo[]>([])
let deptTree = $ref<SysDeptTreeVo[]>([])

// 搜索
const [search, resetClk] = useResetState<SysUserPageQo>(
  { pageNum: 1, pageSize: 10, total: 0 },
  () => {
    loadedTable()
  },
)
// 分页
const { loadedTable, tableData, loading, paginationChange } = useTablePaging(
  getSysUserPageListApi,
  search,
)
// 打开对话框
async function openDialog(action: DialogAction, id?: string) {
  if (!detailsRef)
    return
  const { type } = await detailsRef?.showDialog({
    title: `${DialogActionMap[action]}用户`,
    action,
    model: {
      id,
    },
    roleList,
    postList,
    deptTree,
  })
  if (!type)
    return
  loadedTable()
}

// 删除
const [deleteBatch] = useDeleteBatch($$(selectionList), deleteSysUserApi, () => {
  loadedTable()
  selectionList = []
})
// 启用
const [enable] = useEnable($$(selectionList), enableSysUserApi, () => {
  loadedTable()
  selectionList = []
})
// 禁用
const [disable] = useDisable($$(selectionList), disableSysUserApi, () => {
  loadedTable()
  selectionList = []
})

async function getSelectList() {
  await Promise.all([
    getRoleList(),
    getPostList(),
    getDeptTree(),
  ])
}

async function getRoleList() {
  const res = await getSysRoleListApi({
    status: 1,
  })
  roleList = res.data
}

async function getPostList() {
  const res = await getSysPostListApi({
    status: 1,
  })
  postList = res.data
}

function getDeptTree() {
  getSysDeptTreeApi().then((res) => {
    deptTree = res.data
  })
}

watch(() => search.deptId, () => {
  loadedTable()
})

onMounted(async () => {
  loadedTable()
  await getSelectList()
})
</script>

<template>
  <div
    un-flex="~"
    un-h-full
    un-overflow-hidden
    un-gap="2.5"
  >
    <div
      class="tree"
      un-min-w="300px"
      un-h-full
    >
      <Tree
        v-model="search.deptId"
      />
    </div>
    <div
      un-w="full"
      un-flex="~ col"
      un-h="full"
      un-overflow-hidden
    >
      <el-card
        un-m-b="2.5"
        body-style="height: 100%;"
        style="overflow: visible;"
      >
        <sy-table-query @search="loadedTable" @reset="resetClk">
          <template #default="{ expand }">
            <el-form
              :inline="true"
              :model="search"
              un-grid="~ cols-3 gap-x-5"
              label-width="auto"
              un-items-center
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="search.username" placeholder="请输入名称" clearable />
              </el-form-item>
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="search.phone" placeholder="请输入手机号码" clearable />
              </el-form-item>
              <el-form-item label="昵称" prop="name">
                <el-input v-model="search.name" placeholder="请输入手机号码" clearable />
              </el-form-item>
              <template v-if="expand">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="search.email" placeholder="请输入邮箱" clearable />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <sy-dict
                    v-model="search.sex"
                    dict-type="user_sex"
                    placeholder="请选择性别"
                    type="select"
                  />
                </el-form-item>
                <el-form-item label="角色" prop="roleIdList">
                  <el-select
                    v-model="search.roleIdList"
                    multiple
                    style="width: 100%;"
                    placeholder="请选择角色"
                  >
                    <el-option
                      v-for="item in roleList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="岗位" prop="postIdList">
                  <el-select
                    v-model="search.postIdList"
                    multiple
                    style="width: 100%;"
                    placeholder="请选择岗位"
                    filterable
                  >
                    <el-option
                      v-for="item in postList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                  <sy-dict
                    v-model="search.status"
                    dict-type="status"
                    placeholder="请选择状态"
                    type="select"
                  />
                </el-form-item>
              </template>
            </el-form>
          </template>
        </sy-table-query>
      </el-card>
      <el-card
        un-h-full
        body-style="height: 100%;"
      >
        <sy-table
          v-model:selection="selectionList"
          row-key="id"
          height="100%"
          border
          selection-chenge-use="id"
          :loading="loading"
          :columns="columns"
          :data="tableData"
          :paging="search"
          add-btn-perms="user:add"
          delete-btn-perms="user:delete"
          @paging-change="paginationChange"
          @refresh="loadedTable"
          @click-add="openDialog('add')"
          @click-del="deleteBatch"
        >
          <template #header="{ disabled }">
            <el-button
              v-auth="'user:enabled'"
              plain
              type="primary"
              :disabled
              @click="enable"
            >
              启用
            </el-button>
            <el-button
              v-auth="'user:disable'"
              plain
              type="danger"
              :disabled
              @click="disable"
            >
              禁用
            </el-button>
          </template>
          <template #code="{ row }">
            <el-button
              link
              type="primary"
              @click="openDialog('views', row.id)"
            >
              {{ row.code }}
            </el-button>
          </template>
          <template #operation="{ row }">
            <el-button
              v-auth="'user:edit'"
              link
              type="primary"
              @click="openDialog('edit', row.id)"
            >
              <template #icon>
                <el-icon><Edit /></el-icon>
              </template>
              编辑
            </el-button>
          </template>
        </sy-table>
      </el-card>
    </div>
    <Details ref="detailsRef" />
  </div>
</template>

<style scoped>
:deep .sy-drawer__body {
  padding-top: 0 !important;
}
</style>
